var http = require('../../script/api.js');
var config = require('../../script/config.js');
// var QQMapWX = require('../../qqmap/qqmap-wx-jssdk');
// var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userinfo: null,
    WorkID: '',
    orderInfo: {
      OrderTypeName: '',
      UrgencyName: '',
      SubTypeName: '',
      CreaterName: '',
      ConsName: '',
      PhoneNumber: '',
      Description: '',
      Address: '',
      ProcedureCode: '',
      ProcedureList: [],
      FileList: []
    },
    baseUrl: config.baseUrl,
    ProcedureList: [],
    ProcHandResult: '',
    HandlerResult: '',
    steps: [],
    isShowConfirm: false,
    HuiTui: '',
    showResult: false,
    isShowEditAddress: false,
    NewAddress: '',
    /********** 转派 *********/
    zpShow: false,
    isSelectLastNode: true,
    dataTree: [],
    DEPT_NO: '',
    AssignDeptNo: '',
    HandleUserNo: '',
    /********** 转派 *********/
    /********** 延期 *********/
    yqShow: false,
    yqSubmit: {
      date1: '2025-08.20 15:22',
      date: '',
      remark: '',
    },
    /********** 延期 *********/
    showMorePop: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.WorkID) {
      this.setData({
        WorkID: options.WorkID
      })
    }
    this.getUserInfo()
    this.GetPCode();
    this.getOrderInfo();
    this.GetDeptUserTree();

    // qqmapsdk = new QQMapWX({
    //   key: config.mapKey
    // });
  },

  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo);
      if (value) {
        this.setData({
          userinfo: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // qqmapsdk.reverseGeocoder({
    //   success: (res) => {
    //     this.setData({
    //       areaSelectedStr: res.result.formatted_addresses.recommend
    //     });
    //   }
    // });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},
  GetPCode() {
    http.GetPCode({
      KeyValue: 'ProcHandReason'
    }).then(res => {
      if (res.code === 200) {
        this.setData({
          ProcHandReasonList: res.data
        })
      }
    })
  },
  getOrderInfo: function () {
    if (this.data.WorkID == null || this.data.WorkID == '') return;
    http.GetOrderDetail({
      WorkID: this.data.WorkID,
      ShowWeather: true,
    }).then(res => {
      if (res.code === 200) {
        this.setData({
          orderInfo: res.data,
          HandlerResult: res.data.HandleResult ? res.data.HandleResult : '',
          ProcHandResult: res.data.ProcHandResult ? res.data.ProcHandResult : '1',
          ProcHandReason: res.data.ProcHandReason ? res.data.ProcHandReason : '00'
        })
      }
    });
  },
  HandlerResultChange: function (e) {
    this.setData({
      HandlerResult: e.detail.value
    })
  },
  dealWithOrder: function () {
    let returnData = {};
    const comp = this.selectComponent('.do-component-' + this.data.orderInfo.OrderTypeNo);
    if (comp) {
      returnData = comp.getSubmitData();
    }
    if (returnData) {
      wx.showModal({
        title: '提示',
        content: '确定要提交处理吗？',
        success: (res) => {
          if (res.confirm) {
            const compUpload = this.selectComponent('.upload-component');
            const uploadData = compUpload.getSubmitData();
            const allUpload = uploadData.allUpload;
            const files = uploadData.files;
            if (this.data.orderInfo.NeedFile === 1 && files.length === 0) {
              wx.showToast({
                title: '请先上传图片、视频或录音！',
                icon: 'none',
                duration: 2000
              });
              return;
            }
            if (!allUpload) {
              wx.showModal({
                content: '你有未上传的录音，是否继续上传？',
                cancelText: '否',
                confirmText: '是',
                success: (res) => {
                  if (res.confirm) {
                    return;
                  } else if (res.cancel) {
                    this.submit(returnData, files);
                  }
                }
              })
            } else {
              this.submit(returnData, files);
            }
          }
        }
      })
    }
  },
  submit(returnData, files) {
    const params = {
      OrderID: this.data.orderInfo.OrderID,
      ProcedureCode: this.data.orderInfo.ProcedureCode,
      ProcedureStatus: 2,
      HandlerResult: this.data.HandlerResult,
      ProcHandResult: this.data.ProcHandResult,
      FileList: files,
      HandleWay: 1
    }
    const dataParams = {
      ...params,
      ...returnData
    };
    wx.showLoading({
      mask: true,
      title: '提交处理中...'
    });
    http.UpdateOrderProcedure(dataParams).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 2000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  saveOrder() {
    const compUpload = this.selectComponent('.upload-component');
    const uploadData = compUpload.getSubmitData();
    const allUpload = uploadData.allUpload;
    const files = uploadData.files;
    if (!allUpload) {
      wx.showModal({
        content: '你有未上传的录音，是否继续上传？',
        cancelText: '否',
        confirmText: '是',
        success: (res) => {
          if (res.confirm) {
            return;
          } else if (res.cancel) {
            this.save(files);
          }
        }
      })
    } else {
      this.save(files);
    }
  },
  save() {
    const params = {
      OrderID: this.data.orderInfo.OrderID,
      ProcedureCode: this.data.orderInfo.ProcedureCode,
      ProcedureStatus: 6,
      HandlerResult: this.data.HandlerResult,
      ProcHandResult: this.data.ProcHandResult,
      FileList: files,
      HandleWay: 1
    }
    let returnData = {};
    const comp = this.selectComponent('.do-component-' + this.data.orderInfo.OrderTypeNo);
    if (comp) {
      returnData = comp.getSubmitData(false);
    }
    const dataParams = {
      ...params,
      ...returnData
    };
    wx.showLoading({
      mask: true,
      title: '保存中...'
    });
    http.UpdateOrderProcedure(dataParams).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000
        })
        // this.getOrderInfo()
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
      wx.hideLoading();
    })
  },
  call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone;
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  toMap(e) {
    // var info = e.currentTarget.dataset.info;
    var info = "郑州市红松路252号"
    wx.request({
      method: 'GET',
      url: `https://restapi.amap.com/v3/geocode/geo?output=json&address=${info}&key=${config.amapKey}`,
      success: function (res) {
        if (res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
          const location = res.data.geocodes[0].location;
          if (location) {
            const arr = location.split(',');
            wx.openLocation({
              latitude: arr[0],
              longitude: arr[1],
              scale: 18
            })
          }
        }
      },
    })
    // qqmapsdk.geocoder({
    //   address: info.Address,
    //   success: res => {
    //     wx.openLocation({
    //       latitude: res.result.location.lat,
    //       longitude: res.result.location.lng,
    //       scale: 18
    //     })
    //   }
    // })
    // wx.getLocation({
    //   type: 'gcj02',
    //   success(res) {
    //     const latitude = res.latitude
    //     const longitude = res.longitude
    //     wx.openLocation({
    //       latitude,
    //       longitude,
    //       address: info.Address,
    //       scale: 18
    //     })
    //   }
    // })
  },
  /*********************回退************* */
  back: function () {
    var that = this;
    // wx.navigateBack();
    wx.showModal({
      content: '是否确定回退该工单？',
      success(res) {
        if (res.confirm) {
          that.setData({
            isShowConfirm: true
          })
        }
      }
    })
  },
  //输入框中的值
  setValue: function (e) {
    this.setData({
      HuiTui: e.detail.value
    })
  },
  //点击取消按钮
  cancel: function () {
    var that = this
    that.setData({
      isShowConfirm: false,
    })
  },
  //点击确认按钮
  confirmAcceptance: function () {
    var that = this;
    if (that.data.HuiTui == '') {
      wx.showToast({
        title: '回退原因不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      isShowConfirm: false,
    })
    wx.showLoading({
      mask: true,
      title: '回退处理中...'
    });
    const params = {
      OrderID: that.data.orderInfo.OrderID,
      ProcedureCode: that.data.orderInfo.ProcedureCode,
      ProcedureStatus: 3,
      HandlerResult: that.data.HuiTui,
      HandleWay: 1
    }
    http.UpdateOrderProcedure(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 4000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 3000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  /*********************处理过程************* */
  ResultRadioChange(e) {
    this.setData({
      ProcHandResult: e.detail.value
    })
  },
  /******************地址纠错************* */
  editAddr: function () {
    var that = this;
    that.setData({
      isShowEditAddress: true
    })
  },
  //输入框中的值
  setNewAddr: function (e) {
    this.setData({
      NewAddress: e.detail.value
    })
  },
  //点击取消按钮
  cancelAddr: function () {
    var that = this
    that.setData({
      isShowEditAddress: false,
    })
  },
  //点击确认按钮
  confirmAddr: function () {
    var that = this;
    if (that.data.NewAddress == '') {
      wx.showToast({
        title: '纠错信息不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      isShowEditAddress: false,
    })
    wx.showLoading({
      mask: true,
      title: '提交处理中...'
    });
    let msgContent = '户号：' + that.data.orderInfo.ConsNo
    msgContent += '，户名：' + that.data.orderInfo.ConsName
    msgContent += '，电话号码：' + that.data.orderInfo.PhoneNumber
    msgContent += '，纠错信息：' + that.data.NewAddress
    const params = {
      msgTitle: '用户地址纠错',
      msgContent: msgContent,
      msgType: 1,
      RoleType: '03'
    }
    http.SendMsg(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 4000
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  orderDelay() {
    this.setData({
      yqShow: true,
      showMorePop: false
    })
  },
  orderDispatch() {
    this.setData({
      zpShow: true,
      showMorePop: false
    })
  },
  leave() {
    this.setData({
      yqShow: false,
      zpShow: false
    })
  },
  /***************** 转派 **************/
  GetDeptUserTree() {
    http.GetDeptUserTree({}).then(res => {
      if (res.code === 200) {
        this.setData({
          dataTree: res.data[0].MODELLIST
        })
      }
    })
  },
  handleSelect(e) {
    if (e.detail.tips) {
      console.log('必须选择到最末级节点');
    } else {
      this.setData({
        DEPT_NO: e.detail.item.DEPT_NO,
        AssignDeptNo: e.detail.item.P_DEPT_NO,
        HandleUserNo: e.detail.item.ABBR
      });
    }
  },
  CancelZp() {
    this.setData({
      zpShow: false,
      DEPT_NO: '',
      AssignDeptNo: '',
      HandleUserNo: ''
    });
  },
  DoZp() {
    var that = this;
    if (that.data.AssignDeptNo == '') {
      wx.showToast({
        title: '请选择转派人员！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      zpShow: false,
    })
    wx.showLoading({
      mask: true,
      title: '转派中...'
    });
    const params = {
      OrderID: that.data.orderInfo.OrderID,
      ProcedureCode: that.data.orderInfo.ProcedureCode,
      ProcedureStatus: 4,
      AssignDeptNo: that.data.AssignDeptNo,
      HandleUserNo: that.data.HandleUserNo,
      HandleWay: 1
    }
    http.UpdateOrderProcedure(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 4000,
          success: function () {
            setTimeout(() => {
              wx.navigateBack();
            }, 3000)
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  /***************** 转派 **************/
  /***************** 延期 **************/
  changeDate(e) {
    this.setData({
      'yqSubmit.date': e.detail.value
    })
  },
  remarkChange(e) {
    this.setData({
      'yqSubmit.remark': e.detail.value
    })
  },
  CancelDelay() {
    this.setData({
      yqShow: false,
      'yqSubmit.remark': '',
      'yqSubmit.date': ''
    })
  },
  DoDelay() {

  },
  /***************** 延期 **************/
  showMore(){
    this.setData({
      showMorePop: true
    });
  },
  closeMore(){
    this.setData({
      showMorePop: false
    });
  },
})